const { _log, _err, _setFailed } = require('../utils/log');
const Fs = require('fs-extra');

let corpid = '';
let agentid = '';
let corpsecret = '';
let content = '';

const { post, get } = require('axios').default;

async function get_wechat_config() {
  let bast_config = '';

  if (process.env.CONFIG_URL) {
    try {
      const { data } = await get(process.env.CONFIG_URL);
      bast_config = typeof data === 'string' ? JSON.parse(data) : data;
    } catch (e) {
      _err('CONFIG_URL 配置错误', e.toString());
    }
  } else if (Fs.existsSync('config.json')) {
    try {
      bast_config = Fs.readJsonSync('config.json');
    } catch (e) {
      _err('config.json 格式错误', e.toString());
    }
  }

  const wechat_config = bast_config.wechat_push;
  corpid = wechat_config.corpid;
  agentid = wechat_config.agentid;
  corpsecret = wechat_config.corpsecret;
  content = wechat_config.content;
}

/**
 * {
    "errcode": 0,
    "errmsg": "ok",
    "access_token": "05IsfZzRYQcxZsPxEH7fmWU_Jeyw-mffoi_kGNj4RVIFE1QKaF75eKtrcPCHvxlhluowsfq4FED2OLYHiCJTPrt8ekuEdv8dAS9veT-K7DC8XG0pPuzWigbG3hIak443qO4yJfLMDity5TpotzSdFdaLBiwPucG8DoWFyp0Bszx0ozT06_exahgU-7yLUVDslNB0ncROVqlR2612h_gozQ",
    "expires_in": 7200
}
 */
async function get_token() {
  await get_wechat_config();
  if (corpid && corpsecret) {
    const url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret;
    let access_token = '';
    await post(url).then(res => {
      if (res.data.access_token) {
        access_token = res.data.access_token;
      }
    });
    return access_token;
  }
}

exports.get_token = get_token;

exports.wechat_push = async message => {
  const access_token = await get_token();
  if (access_token) {
    const url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token;
    const body = {
      touser: '@all',
      msgtype: 'text',
      agentid: agentid,
      text: {
        content: '米游社自动签到\n' + (message ? message : content) + '\n' + getdate(),
      },
      duplicate_check_interval: 1800,
    };
    post(url, body).then(() => {
      _log('\n微信推送完成');
    });
  } else {
    _log('\n获取微信token失败');
  }
};

function getdate() {
  var now = new Date(),
    y = now.getFullYear(),
    m = now.getMonth() + 1,
    d = now.getDate();
  return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' ' + now.toTimeString().substr(0, 8);
}
